package com.example.springweb.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springweb.constant.Global;
import com.example.springweb.mapper.ProductMapper;
import com.example.springweb.model.dto.ProductDTO;
import com.example.springweb.model.entity.Product;
import com.example.springweb.model.vo.ProductVo;
import com.example.springweb.service.IProductService;
import cn.hutool.core.util.StrUtil;
import lombok.extern.log4j.Log4j2;

@Log4j2
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
	
	@Autowired
	private ProductMapper productMapper;

	@Cacheable(value = Global.CACHE_PRODUCTS)
	@Override
	public ProductVo getProductById(Long id) {
		return productMapper.findProductById(id);
	}
	
	@Override
	public Product selectById(Long id) {
		return productMapper.selectById(id);
	}

	@Override
	public int insert(Product product) {
		return productMapper.insert(product);
	}

	@Override
	public IPage<ProductVo> findPruductByCategory(ProductDTO dto) {
		try {
			// 分页， 第几页，每页几条
			Page<ProductDTO> page = new Page<>(dto.getCurrent(), dto.getSize());
			IPage<ProductVo> products = productMapper.findPruductByCategory(page, dto);
			return products;
		} catch (Exception e) {
			log.error("查询产品信息时出错", e);
            throw e;
		}
	}

	@Override
	public List<Product> selectList(ProductDTO product) {
		Page<Product> page = new Page<Product>(product.getCurrent(), product.getSize());
		QueryWrapper<Product> wrapper = new QueryWrapper<>();
		if(StrUtil.isNotBlank(product.getCategory())) {
			wrapper.eq("category", product.getCategory());
		}
		if(StrUtil.isNotBlank(product.getProductName())) {
			wrapper.like("product_name", product.getProductName());
		}
		// 排序
		this.orderBy(product.getSort(), wrapper);
		IPage<Product> products = productMapper.selectPage(page, wrapper);
		return products.getRecords();
	}

	

}
